package it.bambo.tankwars.model;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * Andreas Baumgartner: andreas@bambo.it
 */
public class Bullet extends Unit {

    private Tank tank;

    private double sizeFactor = 2;

    private Point startPosition;
    private double towerDirection;
    private int distance = 1;

    public Bullet(BattleField battleField, Tank tank, Point position) {
        super(battleField, new Rectangle(position.x, position.y, 3, 3));
        this.tank = tank;
        tank.getBullets().add(this);
        this.startPosition = new Point(position.x, position.y);
        this.towerDirection = tank.getTowerDirection();
    }

    @Override
    public BufferedImage getImage() {
        updateCoordinates();

        final Unit unit = battleField.intersectsObstacle(this);
        if (unit != null && unit instanceof Tank) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    battleField.getUnits().remove(unit);
                    destroy();
                }
            });
            return null;
        }

        if (battleField.getField().contains(rect)) {
            this.image = new BufferedImage(rect.width + 1, rect.width + 1, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(Color.WHITE);

            graphics.drawOval(0, 0, rect.width, rect.height);

            return this.image;
        } else {
            destroy();
            return null;
        }
    }

    private void destroy() {
        final Bullet bullet = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                tank.getBullets().remove(bullet);
                tank = null;
                battleField.getUnits().remove(bullet);
            }
        });
    }

    private void updateCoordinates() {
        rect.setLocation((int) ((distance / 2) * Math.cos(Math.toRadians(towerDirection))) + startPosition.x,
                (int) ((distance / 2) * Math.sin(Math.toRadians(towerDirection))) + startPosition.y);
    }

    public void fly() {
        distance += 10;
    }
}
